package models

import (
	"fmt"
	"gorm.io/gorm"
)

type Node struct{
	gorm.Model
	Uuid string  `gorm:"unique;not null"`
	UserId int
	User User
	Title string   `gorm:"type:varchar(200)"`
	Summary string `gorm:"type:text"`
	Content string `gorm:"type:text"`
	Visit int      `gorm:"default:0"`
	Praise int		`gorm:"default:0"`
}

func QueryNodeByKey(key string)(num int64,node Node,err error){
	res:=db.Where("Uuid=?",key).Take(&Node{}).Scan(&node)   //查询值并且扫描
	return res.RowsAffected, node,res.Error
}
func QueryNodeByPage(str string,page ,limit int)(nodes []Node,err error){
	res:=db.Where("title like ?",fmt.Sprintf("%%%s%%",str)).Offset((page-1)*limit).Limit(limit).Order("updated_at desc").Find(&nodes)
    return nodes,res.Error
    //扫描分页的数据，并且返回错误
}
func QueryAllCount(str string)(int64,error){
     var count int64
     return count,db.Where("title like ?",fmt.Sprintf("%%%s%%",str)).Model(&Node{}).Count(&count).Error
}
func QueryNodeByUserIdAndKey(userid int,key string)(node Node,err error){
	res:=db.Where("user_id=? and uuid=?",userid,key).First(&node)
	return node,res.Error
}
func SaveNode(node Node)error{
	res:=db.Save(&node)
	return res.Error
}
func DeleteNode(key string,userid int)error{
	 res:=db.Where("uuid=? and user_id=?",key,userid).Delete(&Node{})   //根据key值删除
	 return res.Error
}
